<template>
  <div class="form-editor">
    <!-- 简化的工具栏 -->
    <div class="editor-toolbar">
      <div class="form-info">
        <div class="form-title-edit">
          <el-input 
            v-model="formData.title" 
            placeholder="请输入表单标题"
            class="title-input"
            @blur="saveForm"
            @input="onTitleChange"
            size="large"
          />
        </div>
        <div class="form-description-edit">
          <el-input 
            v-model="formData.description" 
            placeholder="请输入表单描述（可选）"
            class="description-input"
            @blur="saveForm"
            @input="onDescriptionChange"
            type="textarea"
            :rows="1"
            :autosize="{ minRows: 1, maxRows: 2 }"
            resize="none"
          />
        </div>
      </div>
      <div class="toolbar-actions">
        <el-button icon="View" @click="previewForm">预览</el-button>
        <el-button v-if="formData.status === 0" type="success" icon="Upload" @click="publishForm">发布</el-button>
        <el-button v-else-if="formData.status === 1" type="warning" icon="Close" @click="closeForm">关闭</el-button>
        <el-button type="primary" icon="Document" @click="saveForm" :loading="saving">
          {{ saving ? '保存中...' : '保存' }}
        </el-button>
      </div>
    </div>

    <div class="editor-content">
      <!-- 左侧字段面板 -->
      <div class="field-panel">
        <div class="panel-header">
          <h4>字段组件</h4>
        </div>
        <div class="field-types">
          <div class="field-category">
            <h5>基础字段</h5>
            <div class="field-items">
              <div 
                v-for="field in basicFields" 
                :key="field.type"
                class="field-item"
                draggable="true"
                @dragstart="onDragStart($event, field)"
              >
                <el-icon :size="16"><component :is="field.icon" /></el-icon>
                <span>{{ field.label }}</span>
              </div>
            </div>
          </div>
          
          <div class="field-category">
            <h5>选择字段</h5>
            <div class="field-items">
              <div 
                v-for="field in choiceFields" 
                :key="field.type"
                class="field-item"
                draggable="true"
                @dragstart="onDragStart($event, field)"
              >
                <el-icon :size="16"><component :is="field.icon" /></el-icon>
                <span>{{ field.label }}</span>
              </div>
            </div>
          </div>
          
          <div class="field-category">
            <h5>高级字段</h5>
            <div class="field-items">
              <div 
                v-for="field in advancedFields" 
                :key="field.type"
                class="field-item"
                draggable="true"
                @dragstart="onDragStart($event, field)"
              >
                <el-icon :size="16"><component :is="field.icon" /></el-icon>
                <span>{{ field.label }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间编辑区域 -->
      <div class="editor-main">
        <div class="form-canvas">
          <!-- 字段列表 -->
          <div 
            class="fields-container"
            @drop="onDrop"
            @dragover.prevent
            @dragenter.prevent
          >
            <div v-if="formData.fields.length === 0" class="empty-state">
              <el-icon :size="48"><DocumentAdd /></el-icon>
              <p>从左侧拖拽字段到这里开始创建表单</p>
            </div>
            
            <div
              v-for="(field, index) in formData.fields"
              :key="field.id"
              class="field-wrapper"
              :class="{ 
                active: selectedFieldIndex === index,
                'drag-over': dragOverIndex === index
              }"
              :data-width="field.width"
              draggable="true"
              @click="selectField(index)"
              @dragstart="onFieldDragStart($event, index)"
              @dragover="onFieldDragOver($event, index)"
              @dragleave="onFieldDragLeave"
              @drop="onFieldDrop($event, index)"
            >
              <!-- 拖拽手柄 -->
              <div class="drag-handle">
                <el-icon><Operation /></el-icon>
              </div>
              
              <!-- 字段渲染 -->
              <div class="field-render">
                <el-form-item 
                  :label="field.label" 
                  :required="field.required"
                  class="editor-form-item"
                >
                  <!-- 文本输入 -->
                  <el-input 
                    v-if="field.type === 'text' || field.type === 'email' || field.type === 'phone'"
                    :placeholder="field.placeholder"
                    :maxlength="field.maxLength"
                    disabled
                    class="preview-input"
                  />

                  <!-- 多行文本 -->
                  <el-input 
                    v-else-if="field.type === 'textarea'"
                    type="textarea"
                    :placeholder="field.placeholder"
                    :maxlength="field.maxLength"
                    :rows="4"
                    disabled
                    class="preview-input"
                  />

                  <!-- 数字输入 -->
                  <el-input-number 
                    v-else-if="field.type === 'number'"
                    :placeholder="field.placeholder"
                    :min="field.min"
                    :max="field.max"
                    disabled
                    class="preview-input"
                  />

                  <!-- 单选题 -->
                  <el-radio-group 
                    v-else-if="field.type === 'radio'"
                    disabled
                    class="preview-input"
                  >
                    <el-radio 
                      v-for="option in (field.options && field.options.length > 0 ? field.options : [{label: '选项1', value: '1'}, {label: '选项2', value: '2'}])"
                      :key="option.value"
                      :label="option.value"
                    >
                      {{ option.label }}
                    </el-radio>
                  </el-radio-group>

                  <!-- 多选题 -->
                  <el-checkbox-group 
                    v-else-if="field.type === 'checkbox'"
                    disabled
                    class="preview-input"
                  >
                    <el-checkbox 
                      v-for="option in (field.options && field.options.length > 0 ? field.options : [{label: '选项1', value: '1'}, {label: '选项2', value: '2'}])"
                      :key="option.value"
                      :label="option.value"
                    >
                      {{ option.label }}
                    </el-checkbox>
                  </el-checkbox-group>

                  <!-- 下拉选择 -->
                  <el-select 
                    v-else-if="field.type === 'select'"
                    :placeholder="field.placeholder"
                    disabled
                    class="preview-input"
                    style="width: 100%"
                  >
                    <el-option 
                      v-for="option in (field.options && field.options.length > 0 ? field.options : [{label: '选项1', value: '1'}, {label: '选项2', value: '2'}])"
                      :key="option.value"
                      :label="option.label"
                      :value="option.value"
                    />
                  </el-select>

                  <!-- 日期选择 -->
                  <el-date-picker 
                    v-else-if="field.type === 'date'"
                    type="date"
                    placeholder="请选择日期"
                    disabled
                    class="preview-input"
                    style="width: 100%"
                  />

                  <!-- 评分 -->
                  <el-rate 
                    v-else-if="field.type === 'rating'"
                    :max="field.max || 5"
                    disabled
                    class="preview-input"
                  />

                  <!-- 文件上传 -->
                  <el-upload 
                    v-else-if="field.type === 'file'"
                    class="preview-input"
                    drag
                    disabled
                  >
                    <el-icon class="el-icon--upload"><Upload /></el-icon>
                    <div class="el-upload__text">
                      点击或拖拽文件到此处上传
                    </div>
                  </el-upload>

                  <!-- 地理位置 -->
                  <el-input 
                    v-else-if="field.type === 'location'"
                    placeholder="点击选择位置"
                    disabled
                    class="preview-input"
                  >
                    <template #append>
                      <el-button icon="Location" disabled />
                    </template>
                  </el-input>

                  <!-- 默认输入框 -->
                  <el-input 
                    v-else
                    :placeholder="field.placeholder || '输入内容'"
                    disabled
                    class="preview-input"
                  />

                  <div v-if="field.helpText" class="field-help">
                    {{ field.helpText }}
                  </div>
                </el-form-item>
              </div>
              
              <!-- 字段操作按钮 -->
              <div class="field-actions">
                <el-button icon="CopyDocument" size="small" @click.stop="duplicateField(index)">复制</el-button>
                <el-button icon="Delete" size="small" type="danger" @click.stop="deleteField(index)">删除</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧属性面板 -->
      <div class="property-panel">
        <div class="panel-header">
          <h4>字段属性</h4>
        </div>
        
        <div v-if="selectedField" class="property-content">
          <!-- 基础属性 -->
          <div class="property-group">
            <h5>基础设置</h5>
            <el-form label-position="top" size="small">
              <el-form-item label="字段标签">
                <el-input 
                  v-model="selectedField.label" 
                  placeholder="请输入字段标签"
                  @input="updateSelectedField"
                />
              </el-form-item>
              <el-form-item label="占位符">
                <el-input 
                  v-model="selectedField.placeholder" 
                  placeholder="请输入占位符"
                  @input="updateSelectedField"
                />
              </el-form-item>
              <el-form-item label="帮助文本">
                <el-input 
                  v-model="selectedField.helpText" 
                  placeholder="请输入帮助文本"
                  @input="updateSelectedField"
                />
              </el-form-item>
            </el-form>
          </div>

          <!-- 验证规则 -->
          <div class="property-group">
            <h5>验证规则</h5>
            <el-form label-position="top" size="small">
              <el-form-item>
                <el-checkbox 
                  v-model="selectedField.required" 
                  @change="updateSelectedField"
                >
                  必填字段
                </el-checkbox>
              </el-form-item>
              
              <!-- 文本字段特有属性 -->
              <template v-if="selectedField.type === 'text' || selectedField.type === 'textarea'">
                <el-form-item label="最小长度">
                  <el-input-number 
                    v-model="selectedField.minLength" 
                    :min="0" 
                    @change="updateSelectedField"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="最大长度">
                  <el-input-number 
                    v-model="selectedField.maxLength" 
                    :min="0" 
                    @change="updateSelectedField"
                    style="width: 100%"
                  />
                </el-form-item>
              </template>

              <!-- 选择字段特有属性 -->
              <template v-if="['radio', 'checkbox', 'select'].includes(selectedField.type)">
                <el-form-item label="选项设置">
                  <div class="options-editor">
                    <div 
                      v-for="(option, index) in selectedField.options" 
                      :key="index"
                      class="option-item"
                    >
                      <el-input 
                        v-model="option.label" 
                        placeholder="选项文本"
                        @input="updateSelectedField"
                        size="small"
                      />
                      <el-button 
                        icon="Delete" 
                        size="small" 
                        type="danger"
                        @click="removeOption(index)"
                      />
                    </div>
                    <el-button 
                      icon="Plus" 
                      size="small" 
                      @click="addOption"
                      class="add-option-btn"
                    >
                      添加选项
                    </el-button>
                  </div>
                </el-form-item>
              </template>
            </el-form>
          </div>

          <!-- 样式设置 -->
          <div class="property-group">
            <h5>样式设置</h5>
            <el-form label-position="top" size="small">
              <el-form-item label="字段宽度">
                <el-select v-model="selectedField.width" @change="updateSelectedField" style="width: 100%">
                  <el-option label="100%" value="full" />
                  <el-option label="50%" value="half" />
                  <el-option label="33%" value="third" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
        
        <div v-else class="no-selection">
          <el-icon :size="32"><InfoFilled /></el-icon>
          <p>请选择一个字段进行编辑</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  DocumentAdd, InfoFilled,
  Operation
} from '@element-plus/icons-vue'
import { createForm, updateForm, getForm, publishForm as publishFormApi, closeForm as closeFormApi } from '@/plugin/gva_intelligent_form/api/form.js'

const route = useRoute()
const router = useRouter()

// 表单数据
const formData = ref({
  title: '',
  description: '',
  fields: [],
  status: 0
})

// 获取表单ID（支持从params或query获取）
const formId = computed(() => {
  return route.params.id || route.query.id
})

// 选中的字段
const selectedFieldIndex = ref(-1)
const selectedField = computed(() => {
  return selectedFieldIndex.value >= 0 && formData.value.fields && formData.value.fields[selectedFieldIndex.value] 
    ? formData.value.fields[selectedFieldIndex.value] 
    : null
})

// 保存状态
const saving = ref(false)
const saveTimer = ref(null)

// 拖拽状态管理
const dragOverIndex = ref(-1)
const draggedIndex = ref(-1)

// 字段类型定义
const basicFields = ref([
  { type: 'text', label: '单行文本', icon: 'EditPen' },
  { type: 'textarea', label: '多行文本', icon: 'ChatLineRound' },
  { type: 'email', label: '邮箱', icon: 'Message' },
  { type: 'phone', label: '手机号', icon: 'Phone' },
  { type: 'number', label: '数字', icon: 'Operation' }
])

const choiceFields = ref([
  { type: 'radio', label: '单选题', icon: 'Select' },
  { type: 'checkbox', label: '多选题', icon: 'Checked' },
  { type: 'select', label: '下拉选择', icon: 'ArrowDown' }
])

const advancedFields = ref([
  { type: 'date', label: '日期', icon: 'Calendar' },
  { type: 'rating', label: '评分', icon: 'Star' },
  { type: 'file', label: '文件上传', icon: 'Upload' },
  { type: 'location', label: '地理位置', icon: 'Location' }
])



// 拖拽开始
const onDragStart = (event, fieldType) => {
  try {
    // 将字段类型存储到 dataTransfer 中
    event.dataTransfer.setData('application/json', JSON.stringify(fieldType))
    event.dataTransfer.effectAllowed = 'copy'
  } catch (error) {
    console.error('拖拽开始失败:', error)
  }
}

// 字段拖拽开始
const onFieldDragStart = (event, index) => {
  draggedIndex.value = index
  event.dataTransfer.effectAllowed = 'move'
  event.dataTransfer.setData('text/plain', index.toString())
}

// 字段拖拽悬停
const onFieldDragOver = (event, index) => {
  event.preventDefault()
  event.dataTransfer.dropEffect = 'move'
  dragOverIndex.value = index
}

// 字段拖拽离开
const onFieldDragLeave = () => {
  dragOverIndex.value = -1
}

// 字段拖拽放置
const onFieldDrop = (event, targetIndex) => {
  event.preventDefault()
  const sourceIndex = draggedIndex.value
  
  if (sourceIndex !== -1 && sourceIndex !== targetIndex) {
    // 移动字段
    const fields = [...formData.value.fields]
    const [movedField] = fields.splice(sourceIndex, 1)
    fields.splice(targetIndex, 0, movedField)
    
    formData.value.fields = fields
    
    // 更新选中的字段索引
    if (selectedFieldIndex.value === sourceIndex) {
      selectedFieldIndex.value = targetIndex
    } else if (selectedFieldIndex.value > sourceIndex && selectedFieldIndex.value <= targetIndex) {
      selectedFieldIndex.value--
    } else if (selectedFieldIndex.value < sourceIndex && selectedFieldIndex.value >= targetIndex) {
      selectedFieldIndex.value++
    }
    
    // 自动保存
    saveForm()
  }
  
  // 重置拖拽状态
  draggedIndex.value = -1
  dragOverIndex.value = -1
}

// 拖拽放置
const onDrop = (event) => {
  try {
    event.preventDefault()
    
    // 如果正在进行字段排序，不处理新字段添加
    if (draggedIndex.value !== -1) {
      return
    }
    
    // 尝试获取字段类型数据
    const jsonData = event.dataTransfer.getData('application/json')
    if (!jsonData) {
      return
    }
    
    const fieldType = JSON.parse(jsonData)
    addField(fieldType)
  } catch (error) {
    console.error('拖拽放置失败:', error)
    ElMessage.error('添加字段失败')
  }
}

// 添加字段
const addField = (fieldType) => {
  // 确保fields数组存在
  if (!formData.value.fields) {
    formData.value.fields = []
  }
  
  const newField = {
    id: Date.now() + Math.random(),
    type: fieldType.type,
    label: fieldType.label,
    placeholder: '',
    helpText: '',
    required: false,
    width: 'full',
    ...getDefaultFieldConfig(fieldType.type)
  }
  
  formData.value.fields.push(newField)
  selectedFieldIndex.value = formData.value.fields.length - 1
  
  // 自动保存
  saveForm()
}

// 获取默认字段配置
const getDefaultFieldConfig = (type) => {
  const defaults = {
    text: { maxLength: 100 },
    textarea: { maxLength: 500 },
    email: { pattern: 'email' },
    phone: { pattern: 'phone' },
    number: { min: 0, max: 999999 },
    radio: { options: [{ label: '选项1', value: 'option1' }] },
    checkbox: { options: [{ label: '选项1', value: 'option1' }] },
    select: { options: [{ label: '选项1', value: 'option1' }] },
    date: { format: 'YYYY-MM-DD' },
    rating: { max: 5, icon: 'Star' },
    file: { accept: 'image/*', maxSize: 10 }
  }
  return defaults[type] || {}
}

// 选择字段
const selectField = (index) => {
  selectedFieldIndex.value = index
}

// 标题变化处理
const onTitleChange = () => {
  // 延迟保存，避免频繁保存
  clearTimeout(saveTimer.value)
  saveTimer.value = setTimeout(() => {
    saveForm()
  }, 1000)
}

// 描述变化处理
const onDescriptionChange = () => {
  // 延迟保存，避免频繁保存
  clearTimeout(saveTimer.value)
  saveTimer.value = setTimeout(() => {
    saveForm()
  }, 1000)
}



// 更新选中字段
const updateSelectedField = () => {
  if (selectedField.value) {
    // 延迟保存，避免频繁保存
    clearTimeout(saveTimer.value)
    saveTimer.value = setTimeout(() => {
      saveForm()
    }, 500)
  }
}

// 复制字段
const duplicateField = (index) => {
  if (!formData.value.fields || !formData.value.fields[index]) return
  
  const originalField = formData.value.fields[index]
  // 使用深拷贝避免options数组等嵌套对象共享引用
  const duplicatedField = JSON.parse(JSON.stringify(originalField))
  duplicatedField.id = Date.now() + Math.random()
  duplicatedField.label = originalField.label + ' (副本)'
  
  formData.value.fields.splice(index + 1, 0, duplicatedField)
  selectedFieldIndex.value = index + 1
  saveForm()
}

// 删除字段
const deleteField = (index) => {
  if (!formData.value.fields || !formData.value.fields[index]) return
  
  formData.value.fields.splice(index, 1)
  if (selectedFieldIndex.value === index) {
    selectedFieldIndex.value = -1
  } else if (selectedFieldIndex.value > index) {
    selectedFieldIndex.value--
  }
  saveForm()
}

// 添加选项
const addOption = () => {
  if (selectedField.value) {
    if (!selectedField.value.options) {
      selectedField.value.options = []
    }
    const optionIndex = selectedField.value.options.length + 1
    selectedField.value.options.push({
      label: `选项${optionIndex}`,
      value: `option${optionIndex}`
    })
    updateSelectedField()
  }
}

// 删除选项
const removeOption = (index) => {
  if (selectedField.value && selectedField.value.options && selectedField.value.options.length > 1) {
    selectedField.value.options.splice(index, 1)
    updateSelectedField()
  } else {
    ElMessage.warning('至少保留一个选项')
  }
}

// 保存表单
const saveForm = async () => {
  if (saving.value) return
  
  saving.value = true
  try {
    const data = {
      title: formData.value.title || '未命名表单',
      description: formData.value.description || '',
      formConfig: {
        fields: formData.value.fields || []
      },
      themeConfig: {},
      status: formData.value.status || 0,
      submitLimit: 0,
      isPublic: true,
      password: ''
    }
    
    if (formId.value) {
      // 更新现有表单
      data.id = parseInt(formId.value)
      const res = await updateForm(data)
      if (res.code === 0) {
        ElMessage.success('保存成功')
      }
    } else {
      // 创建新表单
      const res = await createForm(data)
      if (res.code === 0) {
        ElMessage.success('创建成功') 
        // 创建成功后跳转到编辑页面
        router.replace({ name: 'formEditor', query: { id: res.data.ID } })
      }
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败：' + (error.message || '未知错误'))
  } finally {
    saving.value = false
  }
}

// 预览表单
const previewForm = async () => {
  if (formId.value) {
    // 使用组件名称跳转到预览页面
    router.push({ 
      name: 'formPreview', 
      query: { id: formId.value, from: 'editor' }
    })
  } else {
    // 如果没有表单ID，先保存表单
    try {
      await saveForm()
      if (formId.value) {
        router.push({ 
          name: 'formPreview', 
          query: { id: formId.value, from: 'editor' }
        })
      } else {
        ElMessage.warning('保存表单失败，无法预览')
      }
    } catch (error) {
      ElMessage.error('保存表单失败：' + error.message)
    }
  }
}

// 发布表单
const publishForm = async () => {
  if (!formData.value.title) {
    ElMessage.warning('请输入表单标题')
    return
  }
  
  if (formData.value.fields.length === 0) {
    ElMessage.warning('请至少添加一个字段')
    return
  }
  
  try {
    await ElMessageBox.confirm('发布后用户即可开始填写表单，确定要发布吗？', '发布表单', {
      confirmButtonText: '发布',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await publishFormApi({ id: parseInt(formId.value) })
    ElMessage.success('表单发布成功')
    formData.value.status = 1
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发布失败：' + error.message)
    }
  }
}

// 关闭表单
const closeForm = async () => {
  try {
    await ElMessageBox.confirm('关闭后将无法继续接收新的提交，确定要关闭吗？', '关闭表单', {
      confirmButtonText: '关闭',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await closeFormApi({ id: parseInt(formId.value) })
    ElMessage.success('表单已关闭')
    formData.value.status = 2
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('关闭失败：' + error.message)
    }
  }
}



// 加载表单数据
const loadForm = async () => {
  if (formId.value) {
    try {
      const res = await getForm({ id: parseInt(formId.value) })
      if (res.code === 0) {
        // 从formConfig中提取fields，确保fields始终是数组
        const formConfig = res.data.formConfig || {}
        const fields = formConfig.fields || []
        
        formData.value = {
          title: res.data.title || '',
          description: res.data.description || '',
          status: res.data.status || 0,
          fields: fields
        }
      }
    } catch (error) {
      ElMessage.error('加载表单失败：' + error.message)
    }
  }
}

onMounted(() => {
  loadForm()
})

// 组件卸载时清理定时器
onUnmounted(() => {
  if (saveTimer.value) {
    clearTimeout(saveTimer.value)
  }
})
</script>

<style scoped>
.form-editor {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  background: #f8fafc;
}

/* 简化的工具栏 */
.editor-toolbar {
  background: white;
  padding: 16px 20px;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.form-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-width: 500px;
}

.form-title-edit {
  display: flex;
  align-items: center;
}

.title-input {
  font-size: 18px;
  font-weight: 600;
  width: 100%;
}

.title-input :deep(.el-input__wrapper) {
  border: 1px solid #d1d5db;
  background: white;
  border-radius: 8px;
  padding: 12px 16px;
  transition: all 0.2s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.title-input :deep(.el-input__wrapper):hover {
  border-color: #9ca3af;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
}

.title-input :deep(.el-input__wrapper.is-focus) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.title-input :deep(.el-input__inner) {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.form-description-edit {
  display: flex;
  flex-direction: column;
}

.description-input {
  font-size: 14px;
  width: 100%;
}

.description-input :deep(.el-textarea__inner) {
  border: 1px solid #d1d5db;
  background: white;
  border-radius: 6px;
  padding: 8px 12px;
  transition: all 0.2s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  font-size: 14px;
  color: #6b7280;
  resize: none;
}

.description-input :deep(.el-textarea__inner):hover {
  border-color: #9ca3af;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
}

.description-input :deep(.el-textarea__inner):focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.toolbar-actions {
  display: flex;
  gap: 8px;
  align-items: flex-start;
  flex-shrink: 0;
}

/* 编辑器内容区域 */
.editor-content {
  flex: 1;
  display: flex;
  min-height: 0;
}

/* 左侧字段面板 */
.field-panel {
  width: 260px;
  background: white;
  border-right: 1px solid #e5e7eb;
  overflow-y: auto;
}

.panel-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e5e7eb;
  background: #f9fafb;
}

.panel-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.field-types {
  padding: 16px;
}

.field-category {
  margin-bottom: 20px;
}

.field-category h5 {
  margin: 0 0 8px 0;
  font-size: 12px;
  font-weight: 600;
  color: #6b7280;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.field-items {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.field-item {
  display: flex;
  align-items: center;
  padding: 10px 12px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  cursor: grab;
  transition: all 0.2s ease;
  background: white;
  gap: 8px;
}

.field-item:hover {
  border-color: #3b82f6;
  background: #eff6ff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.field-item:active {
  cursor: grabbing;
}

.field-item span {
  font-size: 13px;
  font-weight: 500;
  color: #374151;
  pointer-events: none;
}

.field-item .el-icon {
  pointer-events: none;
  color: #3b82f6;
  font-size: 16px;
}

/* 中间编辑区域 */
.editor-main {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.form-canvas {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  min-height: 500px;
  border: 1px solid #e5e7eb;
}

.fields-container {
  padding: 20px;
  min-height: 400px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #9ca3af;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  margin: 20px 0;
}

.empty-state .el-icon {
  color: #d1d5db;
  margin-bottom: 12px;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
}

.field-wrapper {
  position: relative;
  margin-bottom: 16px;
  padding: 20px;
  background: white;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.field-wrapper:hover {
  border-color: #c0c4cc;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.field-wrapper.active {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.field-wrapper.drag-over {
  border-color: #67c23a;
  background-color: #f0f9ff;
  transform: translateY(-2px);
}

/* 拖拽手柄 */
.drag-handle {
  position: absolute;
  left: -2px;
  top: 50%;
  transform: translateY(-50%);
  width: 20px;
  height: 40px;
  background: #409eff;
  border-radius: 0 4px 4px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: grab;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.field-wrapper:hover .drag-handle {
  opacity: 1;
}

.drag-handle:active {
  cursor: grabbing;
}

.drag-handle .el-icon {
  font-size: 12px;
}

/* 字段渲染区域 */
.field-render {
  margin-bottom: 16px;
  margin-left: 8px;
}

/* 字段标签 */
.field-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #303133;
}

.required-mark {
  color: #f56c6c;
  margin-left: 4px;
}

.field-input {
  margin-bottom: 8px;
}

.field-help {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.field-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  display: none;
  gap: 8px;
}

.field-wrapper:hover .field-actions,
.field-wrapper.active .field-actions {
  display: flex;
}

/* 右侧属性面板 */
.property-panel {
  width: 280px;
  background: white;
  border-left: 1px solid #e5e7eb;
  overflow-y: auto;
}

.property-content {
  padding: 16px;
}

.property-group {
  margin-bottom: 20px;
  padding: 16px;
  background: #f9fafb;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.property-group:last-child {
  margin-bottom: 0;
}

.property-group h5 {
  margin: 0 0 12px 0;
  font-size: 13px;
  font-weight: 600;
  color: #374151;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.options-editor {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-item {
  display: flex;
  gap: 8px;
  align-items: center;
}

.add-option-btn {
  width: 100%;
  margin-top: 8px;
}

.no-selection {
  padding: 40px 20px;
  text-align: center;
  color: #9ca3af;
  margin: 20px;
}

.no-selection .el-icon {
  color: #d1d5db;
  margin-bottom: 12px;
}

.no-selection p {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
}

/* 编辑器表单项样式 */
.editor-form-item {
  margin-bottom: 0;
}

.editor-form-item :deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
}

/* 预览输入框样式 */
.preview-input {
  pointer-events: none;
}

.preview-input :deep(.el-input__wrapper) {
  background-color: #f5f7fa;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.preview-input :deep(.el-textarea__inner) {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
}

.preview-input :deep(.el-input-number) {
  width: 100%;
}

.preview-input :deep(.el-input-number .el-input__wrapper) {
  background-color: #f5f7fa;
}

.preview-input :deep(.el-radio),
.preview-input :deep(.el-checkbox) {
  margin-right: 24px;
  margin-bottom: 8px;
  pointer-events: none;
}

.preview-input :deep(.el-select .el-input__wrapper) {
  background-color: #f5f7fa;
}

.preview-input :deep(.el-date-editor .el-input__wrapper) {
  background-color: #f5f7fa;
}

.preview-input :deep(.el-rate) {
  pointer-events: none;
}

.preview-input :deep(.el-upload) {
  pointer-events: none;
}

.preview-input :deep(.el-upload-dragger) {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
  border-style: dashed;
}

.preview-input :deep(.el-button) {
  pointer-events: none;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .property-panel {
    width: 260px;
  }
  
  .field-panel {
    width: 240px;
  }
  
  .form-info {
    max-width: 400px;
  }
}

@media (max-width: 1024px) {
  .editor-toolbar {
    flex-direction: column;
    gap: 16px;
  }
  
  .form-info {
    max-width: none;
  }
  
  .toolbar-actions {
    justify-content: flex-end;
  }
  
  .editor-content {
    flex-direction: column;
  }
  
  .field-panel {
    width: 100%;
    max-height: 200px;
    border-right: none;
    border-bottom: 1px solid #e5e7eb;
  }
  
  .property-panel {
    width: 100%;
    max-height: 200px;
    border-left: none;
    border-top: 1px solid #e5e7eb;
  }
  
  .editor-main {
    padding: 16px;
  }
}

@media (max-width: 768px) {
  .editor-toolbar {
    padding: 12px 16px;
  }
  
  .form-info {
    gap: 8px;
  }
  
  .toolbar-actions {
    flex-wrap: wrap;
    gap: 6px;
  }
  
  .toolbar-actions .el-button {
    flex: 1;
    min-width: 70px;
  }
  
  .fields-container {
    padding: 16px;
  }
  
  .field-panel,
  .property-panel {
    max-height: 180px;
  }
  
  .title-input :deep(.el-input__wrapper) {
    padding: 16px;
  }
  
  .title-input :deep(.el-input__inner) {
    font-size: 16px;
  }
}
</style>